﻿using System;
using System.Collections.Generic;
using System.Numerics;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Rendering;
using Random = UnityEngine.Random;
using Vector3 = UnityEngine.Vector3;
// ReSharper disable CheckNamespace

public class CardDeck : SingletonMono<CardDeck>
{
    public CardManager cardManager;
    public CardLibrarySO selectedCardLibrary;
    private List<BuildingChessDateSO> drawDeckPlayer1 = new();
    private List<BuildingChessDateSO> discardDeckPlayer1 = new();
    
    private List<BuildingChessDateSO> drawDeckPlayer2 = new();
    private List<BuildingChessDateSO> discardDeckPlayer2 = new();

    public List<Card> player1HandCardList = new();
    public List<Card> player2HandCardList = new();

    public Vector3 deckPosition;

    /// <summary>
    /// Awake is called when the script instance is being loaded.
    /// </summary>
    private void OnEnable()
    {
        //TODO:测试用初始化卡组
        EventCenter.GetInstance().AddEventListener<Card,ChessSide>(nameof(DiscardCard), DiscardCard);
        EventCenter.GetInstance().AddEventListener<Card,ChessSide>(nameof(FailedToUse), FailedToUse);
        EventCenter.GetInstance().AddEventListener<int,ChessSide>(nameof(DrawCard), DrawCard);
    }

    /// <summary>
    /// This function is called when the behaviour becomes disabled or inactive.
    /// </summary>
    private void OnDisable()
    {
        EventCenter.GetInstance().RemoveEventListener<Card,ChessSide>(nameof(DiscardCard), DiscardCard);
        EventCenter.GetInstance().RemoveEventListener<Card,ChessSide>(nameof(FailedToUse), FailedToUse);
        EventCenter.GetInstance().RemoveEventListener<int,ChessSide>(nameof(DrawCard), DrawCard);
    }
    

    public void InitDeck(CardLibrarySO enemyCardLibrary) //初始化卡组
    {
        drawDeckPlayer1.Clear();
        drawDeckPlayer2.Clear();
        foreach (var cardDate in selectedCardLibrary.cardLibraryList)
        {   
            drawDeckPlayer1.Add(cardDate);
        }
        foreach (var cardDate in enemyCardLibrary.cardLibraryList)
        {   
            drawDeckPlayer2.Add(cardDate);
        }
        ShuffleDeck(ChessSide.Player1);    
        ShuffleDeck(ChessSide.Player2);    
    }

    public void DrawCard(int count,ChessSide side) //抽卡
    {
        var handCards = side == ChessSide.Player1 ? player1HandCardList : player2HandCardList;
        var drawCard = side == ChessSide.Player1 ? drawDeckPlayer1 : drawDeckPlayer2;
        var discardDeck = side == ChessSide.Player1 ? discardDeckPlayer1 : discardDeckPlayer2;
        for (int i = 0; i < count; i++)
        {
            
            if (drawCard.Count == 0)
            {
                foreach (var item in discardDeck)
                {
                    drawCard.Add(item);
                }
                ShuffleDeck(side);
            }
            if (drawCard.Count == 0)
            {
                if (side == ChessSide.Player2)
                {
                    EventCenter.GetInstance().EventTrigger("Player2TurnBegin");
                }
                print("卡牌抽光了");
                return;
            }

            BuildingChessDateSO currentCardDate = drawCard[0];
            drawCard.RemoveAt(0);
            var go = cardManager.GetCardObject();
            var card = go.GetComponent<Card>();
            //卡牌初始化
            card.Init(currentCardDate,side);
            card.transform.position = deckPosition;
            handCards.Add(card);

            var delay = i *0.2f;
            SetCardLayout(side,delay);
        }
        if (side == ChessSide.Player2)
        {
            EventCenter.GetInstance().EventTrigger("Player2TurnBegin");
        }
    }

    private void SetCardLayout(ChessSide  side,float delay = 0.1f)
    {
        var handCards = side == ChessSide.Player1 ? player1HandCardList : player2HandCardList;
        for (int i = 0; i < handCards.Count; i++)
        {
            Card currentCard = handCards[i];

            Vector3 currentCardPosition = CardLayoutManager.GetInstance().GetCardTransform(i, handCards.Count,side);

            currentCard.UpdateCardState();
            
            //设置卡牌正在动画中
            currentCard.isAnimating = true;
            Settings.canBeUsed = false;

            //设置卡牌的缩放动画
            currentCard.transform.DOScale(Vector3.one, 0.2f).SetDelay(delay).onComplete = ()=>
            {
                //设置卡牌的移动动画
                currentCard.transform.DOMove(currentCardPosition, 0.5f).OnComplete(() => 
                {
                    currentCard.isAnimating = false;
                    Settings.canBeUsed = true;
                    currentCard.boxCollider2D.enabled = true;
                });;
            };

            //设置卡牌层级
            currentCard.GetComponent<SortingGroup>().sortingOrder = i;

            //更新卡牌的位置和旋转
            currentCard.UpdatePositionRotation(currentCardPosition, UnityEngine.Quaternion.identity);
        }
    }

    public void GameOver()
    {
        foreach(var card in player1HandCardList)
        {
            cardManager.DiscardCard(card.gameObject);
        }
        foreach (var card in player2HandCardList)
        {
            cardManager.DiscardCard(card.gameObject);
        }
        drawDeckPlayer1.Clear();
        drawDeckPlayer2.Clear();
        discardDeckPlayer1.Clear();
        discardDeckPlayer2.Clear();
        player1HandCardList.Clear();
        player2HandCardList.Clear();
    }

    // ReSharper disable Unity.PerformanceAnalysis
    private void DiscardCard(Card card,ChessSide side)
    {
        var discardDeck = side == ChessSide.Player1 ? discardDeckPlayer1 : discardDeckPlayer2;
        var handCards = side == ChessSide.Player1 ? player1HandCardList : player2HandCardList;
        // 将牌的日期对象添加到弃牌堆中
        discardDeck.Add(card.buildingDate);
        // 从手牌对象列表中移除该牌
        handCards.Remove(card);

        // 调用卡管理器中的DiscardCard方法，将牌从场景中移除
        card.DiscardResourcesPoint();
        cardManager.DiscardCard(card.gameObject);
        
        // 设置卡牌布局，参数为0f
        SetCardLayout(side,0f);
    }

    private void FailedToUse(Card card,ChessSide side)
    {
        print(1);
        var discardDeck = side == ChessSide.Player1 ? discardDeckPlayer1 : discardDeckPlayer2;
        var handCards = side == ChessSide.Player1 ? player1HandCardList : player2HandCardList;
        var date = card.buildingDate;
        var i = card.originLayerOrder;
        discardDeck.Remove(date);
        
        var newCard = cardManager.GetCardObject().GetComponent<Card>();
        //卡牌初始化
        newCard.Init(date,side);
        newCard.transform.position = deckPosition;
        
        handCards.Insert(i, newCard);

        
        SetCardLayout(side);
    }
    
    private void ShuffleDeck(ChessSide side)
    {
        var discardDeck = side == ChessSide.Player1 ? discardDeckPlayer1 : discardDeckPlayer2;
        var drawCard = side == ChessSide.Player1 ? drawDeckPlayer1 : drawDeckPlayer2;
        discardDeck.Clear();
        

        for (int i = 0; i < drawCard.Count; i++)
        {
            BuildingChessDateSO temp = drawCard[i];
            int randomIndex = Random.Range(i, drawCard.Count);
            drawCard[i] = drawCard[randomIndex];
            drawCard[randomIndex] = temp;
        }
    }
}
